﻿using System.Collections.Specialized;
using System.ComponentModel.Composition;
using DevExpress.Xpf.Docking;
using Microsoft.Practices.Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JXPlatform.Infrastructure.RegionAdapters
{
    [Export]
    public class DocumentGroupRegionAdapter : RegionAdapterBase<DocumentGroup>
    {
        private DocumentGroup _regionTarget;
        private IRegion _region;

        [ImportingConstructor]
        public DocumentGroupRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
            :base(regionBehaviorFactory)
        {

        }

        protected override void Adapt(IRegion region, DocumentGroup regionTarget)
        {
            if (regionTarget == null)
            {
                throw new ArgumentNullException("regionTarget");
            }

            if (regionTarget.Items.Count != 0)
            {
                throw new InvalidOperationException();
            }

            _regionTarget = regionTarget;
            _region = region;
            region.ActiveViews.CollectionChanged += ActiveViewsOnCollectionChanged;
            region.Views.CollectionChanged += ViewsOnCollectionChanged;
        }

        private void ViewsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems == null)
            {
                return;
            }

            _region.Activate(e.NewItems[0]);
        }

        private void ActiveViewsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems == null)
            {
                return;
            }

            var layoutPanel = _regionTarget.Items.FirstOrDefault(r => ((LayoutPanel) r).Content == e.NewItems[0]);
            if (layoutPanel == null)
            {
                layoutPanel = new LayoutPanel {Content = e.NewItems[0]};
                _regionTarget.Add(layoutPanel);
            }

            layoutPanel.IsActive = true;
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }
}
